<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="主体名称" prop="entityName">
              <el-input v-model="queryParams.entityName" placeholder="请输入主体名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="法人姓名" prop="legalPersonName">
              <el-input v-model="queryParams.legalPersonName" placeholder="请输入法人姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="主体类型" prop="entityType">
              <el-select v-model="queryParams.entityType" placeholder="请选择主体类型" clearable>
                <el-option v-for="dict in sys_entity_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="等级" prop="level">
              <el-select v-model="queryParams.level" placeholder="请选择等级" clearable>
                <el-option v-for="dict in sys_entity_level" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="渠道来源" prop="channelSource">
              <el-select v-model="queryParams.channelSource" placeholder="请选择渠道来源" clearable>
                <el-option v-for="dict in sys_channel_sourse" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
         
            <el-form-item label="市" prop="city">
              <el-input v-model="queryParams.city" placeholder="请输入市" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="县/区" prop="districtCounty">
              <el-input v-model="queryParams.districtCounty" placeholder="请输入县/区" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="认证状态" prop="certificationStatus">
              <el-select v-model="queryParams.certificationStatus" placeholder="请选择认证状态" clearable>
                <el-option v-for="dict in sys_certified_state" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['Nyt7BusinessEntity:Nyt7BusinessEntity:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate()"
              v-hasPermi="['Nyt7BusinessEntity:Nyt7BusinessEntity:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['Nyt7BusinessEntity:Nyt7BusinessEntity:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['Nyt7BusinessEntity:Nyt7BusinessEntity:export']"
              >导出</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleImport" v-hasPermi="['Nyt7BusinessEntity:Nyt7BusinessEntity:add']"
              >导入</el-button
            >
          </el-col>

          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="Nyt7BusinessEntityList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
        <el-table-column label="主体名称" align="center" prop="entityName" />
        <el-table-column label="法人姓名" align="center" prop="legalPersonName" />
        <el-table-column label="手机号" align="center" prop="phoneNumber" />
        <el-table-column label="主体类型" align="center" prop="entityType">
          <template #default="scope">
            <dict-tag :options="sys_entity_type" :value="scope.row.entityType" />
          </template>
        </el-table-column>
        <el-table-column label="等级" align="center" prop="level">
          <template #default="scope">
            <dict-tag :options="sys_entity_level" :value="scope.row.level" />
          </template>
        </el-table-column>
        <el-table-column label="渠道来源" align="center" prop="channelSource">
          <template #default="scope">
            <dict-tag :options="sys_channel_sourse" :value="scope.row.channelSource" />
          </template>
        </el-table-column>

        <el-table-column label="市" align="center" prop="city" />
        <el-table-column label="区/县" align="center" prop="districtCounty" />
        <el-table-column label="认证状态" align="center" prop="certificationStatus">
          <template #default="scope">
            <dict-tag :options="sys_certified_state" :value="scope.row.certificationStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <template v-if="scope.row.certificationStatus === '已认证'">
              <el-tooltip content="取消认证" placement="top">
                <el-button link type="primary" icon="Close" @click="handleCancelCertification(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改经营主体对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="Nyt7BusinessEntityFormRef" :model="form" :rules="rules" label-width="120px" :disabled="dialog.type === 'view'">
        <el-form-item label="主体名称" prop="entityName">
          <el-input v-model="form.entityName" placeholder="请输入主体名称" />
        </el-form-item>
        <el-form-item label="法人姓名" prop="legalPersonName">
          <el-input v-model="form.legalPersonName" placeholder="请输入法人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="主体类型" prop="entityType">
          <el-select v-model="form.entityType" placeholder="请选择主体类型">
            <el-option v-for="dict in sys_entity_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择等级">
            <el-option v-for="dict in sys_entity_level" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道来源" prop="channelSource">
          <el-select v-model="form.channelSource" placeholder="请选择渠道来源">
            <el-option v-for="dict in sys_channel_sourse" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <!-- 市县改为下拉框 -->
        <el-form-item label="市" prop="city">
          <el-select v-model="form.city" placeholder="请选择市" @change="handleCityChange">
            <el-option v-for="city in cityOptions" :key="city.regionId" :label="city.regionName" :value="city.regionName" />
          </el-select>
        </el-form-item>
        <el-form-item label="县/区" prop="districtCounty">
          <el-select v-model="form.districtCounty" placeholder="请选择县/区">
            <el-option v-for="county in countyOptions" :key="county.regionId" :label="county.regionName" :value="county.regionName" />
          </el-select>
        </el-form-item>
        <el-form-item label="认证状态" prop="certificationStatus">
          <el-select v-model="form.certificationStatus" placeholder="请选择认证状态">
            <el-option v-for="dict in sys_certified_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经营业务" prop="businessScope">
          <el-input v-model="form.businessScope" placeholder="请输入经营业务" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker clearable v-model="form.birthDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-input v-model="form.education" placeholder="请输入学历" />
        </el-form-item>
        <el-form-item label="备用联系方式" prop="backupContact">
          <el-input v-model="form.backupContact" placeholder="请输入备用联系方式" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input v-model="form.idCardNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="详细所在地" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细所在地" />
        </el-form-item>
        <el-form-item label="工商执照号" prop="businessLicenseNumber">
          <el-input v-model="form.businessLicenseNumber" placeholder="请输入工商执照号" />
        </el-form-item>
        <el-form-item label="注册资金（万）" prop="registeredCapital">
          <el-input v-model="form.registeredCapital" placeholder="请输入注册资金" />
        </el-form-item>
        <el-form-item label="工商注册时间" prop="businessRegistrationDate">
          <el-date-picker
            clearable
            v-model="form.businessRegistrationDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择工商注册时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen" width="400px" append-to-body>
      <el-upload 
        ref="uploadRef"
        class="upload-demo"
        :auto-upload="false"
        :on-change="handleChange"
        :limit="1"
        accept=".xlsx,.xls">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">上传</el-button>
        <template #tip>
          <div class="el-upload__tip">上传文件仅支持，xls/xlsx格式，文件大小不得超过20M</div>
        </template>
      </el-upload>
    </el-dialog>
    <!-- 查看对话框 -->
    <el-dialog title="查看经营主体" v-model="viewDialog.visible" width="800px" append-to-body>
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span class="title">个人资料</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="昵称">{{ form.nickname }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ form.phoneNumber }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ form.birthDate }}</el-descriptions-item>
          <el-descriptions-item label="学历">{{ form.education }}</el-descriptions-item>
          <el-descriptions-item label="备用联系方式">{{ form.backupContact }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span class="title">经营主体信息</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="主体名称">{{ form.entityName }}</el-descriptions-item>
          <el-descriptions-item label="法人姓名">{{ form.legalPersonName }}</el-descriptions-item>
          <el-descriptions-item label="主体类型">
            <dict-tag :options="sys_entity_type" :value="form.entityType" />
          </el-descriptions-item>
          <el-descriptions-item label="经营业务">{{ form.businessScope }}</el-descriptions-item>
          <el-descriptions-item label="等级">
            <dict-tag :options="sys_entity_level" :value="form.level" />
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ form.idCardNumber }}</el-descriptions-item>
          <el-descriptions-item label="详细所在地">{{ form.detailedAddress }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card>
        <template #header>
          <div class="card-header">
            <span class="title">工商信息</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工商执照号">{{ form.businessLicenseNumber }}</el-descriptions-item>
          <el-descriptions-item label="注册资金">{{ form.registeredCapital }}</el-descriptions-item>
          <el-descriptions-item label="工商注册时间">{{ form.businessRegistrationDate }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Nyt7BusinessEntity" lang="ts">
import {
  listNyt7BusinessEntity,
  getNyt7BusinessEntity,
  delNyt7BusinessEntity,
  addNyt7BusinessEntity,
  updateNyt7BusinessEntity,
  cancelCertification,
  importExcel
} from '@/api/Nyt7BusinessEntity/Nyt7BusinessEntity';
import { Nyt7BusinessEntityVO, Nyt7BusinessEntityQuery, Nyt7BusinessEntityForm } from '@/api/Nyt7BusinessEntity/Nyt7BusinessEntity/types';
import { Nyt7RegionManagementVO } from '@/api/Nyt7RegionManagement/Nyt7RegionManagement/types';
import { listNyt7RegionManagement } from '@/api/Nyt7RegionManagement/Nyt7RegionManagement';
import { getToken } from '@/utils/auth';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_certified_state, sys_entity_level, sys_entity_type, sys_channel_sourse } = toRefs<any>(
  proxy?.useDict('sys_certified_state', 'sys_entity_level', 'sys_entity_type', 'sys_channel_sourse')
);

const Nyt7BusinessEntityList = ref<Nyt7BusinessEntityVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const regionManagementList = ref<Nyt7RegionManagementVO[]>([]);
const cityOptions = ref<Nyt7RegionManagementVO[]>([]);
const countyOptions = ref<Nyt7RegionManagementVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const Nyt7BusinessEntityFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const viewDialog = reactive<DialogOption>({
  visible: false
});

const initFormData: Nyt7BusinessEntityForm = {
  id: undefined,
  entityName: undefined,
  legalPersonName: undefined,
  phoneNumber: undefined,
  entityType: undefined,
  level: undefined,
  channelSource: undefined,
  province: undefined,
  city: undefined,
  districtCounty: undefined,
  certificationStatus: undefined,
  businessScope: undefined,
  nickname: undefined,
  birthDate: undefined,
  education: undefined,
  backupContact: undefined,
  idCardNumber: undefined,
  detailedAddress: undefined,
  businessLicenseNumber: undefined,
  registeredCapital: undefined,
  businessRegistrationDate: undefined
};
const data = reactive<PageData<Nyt7BusinessEntityForm, Nyt7BusinessEntityQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    entityName: undefined,
    legalPersonName: undefined,
    phoneNumber: undefined,
    entityType: undefined,
    level: undefined,
    channelSource: undefined,
    province: undefined,
    city: undefined,
    districtCounty: undefined,
    certificationStatus: undefined,
    params: {}
  },
  rules: {
    entityName: [{ required: true, message: '主体名称不能为空', trigger: 'blur' }],
    legalPersonName: [{ required: true, message: '法人姓名不能为空', trigger: 'blur' }],
    phoneNumber: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
    entityType: [{ required: true, message: '主体类型不能为空', trigger: 'change' }],
    level: [{ required: true, message: '等级不能为空', trigger: 'change' }],
    channelSource: [{ required: true, message: '渠道来源不能为空', trigger: 'change' }],
    city: [{ required: true, message: '市不能为空', trigger: 'blur' }],
    districtCounty: [{ required: true, message: '区/县不能为空', trigger: 'blur' }],
    certificationStatus: [{ required: true, message: '认证状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询经营主体列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNyt7BusinessEntity(queryParams.value);
  Nyt7BusinessEntityList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  Nyt7BusinessEntityFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: Nyt7BusinessEntityVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加经营主体';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: Nyt7BusinessEntityVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getNyt7BusinessEntity(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改经营主体';
};

/** 提交按钮 */
const submitForm = () => {
  Nyt7BusinessEntityFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateNyt7BusinessEntity(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addNyt7BusinessEntity(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: Nyt7BusinessEntityVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除经营主体编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delNyt7BusinessEntity(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'Nyt7BusinessEntity/Nyt7BusinessEntity/export',
    {
      ...queryParams.value
    },
    `Nyt7BusinessEntity_${new Date().getTime()}.xlsx`
  );
};

/* 打开数据导入的对话框 */
const excelOpen = ref(false);

function handleImport() {
  excelOpen.value = true;
}

// 存储选择的文件
const selectedFile = ref(null);

// 文件选择变化时的处理
const handleChange = (file) => {
  selectedFile.value = file.raw;
};

// 提交上传
const submitUpload = async () => {
  if (!selectedFile.value) {
    proxy?.$modal.msgError('请先选择文件');
    return;
  }

  try {
    proxy?.$modal.loading('正在上传excel，请稍候...');
    const res = await importExcel(selectedFile.value);
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('上传excel成功');
      excelOpen.value = false;
      getList();
    } else {
      proxy?.$modal.msgError(res.msg);
    }
  } catch (error) {
    proxy?.$modal.msgError('上传excel失败');
  } finally {
    proxy.$modal.closeLoading();
    uploadRef.value.clearFiles();
  }
};

/** 查看按钮操作 */
const handleView = async (row: Nyt7BusinessEntityVO) => {
  reset();
  const res = await getNyt7BusinessEntity(row.id);
  Object.assign(form.value, res.data);
  viewDialog.visible = true;
};

//处理市的选择变化
const handleCityChange = (cityName: string) => {
  const selectedCity = cityOptions.value.find((city) => city.regionName === cityName);
  if (selectedCity) {
    countyOptions.value = regionManagementList.value.filter((item) => item.parentId === selectedCity.regionId);
  } else {
    countyOptions.value = [];
  }
};
//获取区域管理数据的方法
const getRegionManagementList = async () => {
  const res = await listNyt7RegionManagement();
  regionManagementList.value = res.data;
  cityOptions.value = regionManagementList.value.filter((item) => item.parentId === 130000); // 假设parentId为0的是市
};

/** 取消认证操作 */
const handleCancelCertification = async (row: Nyt7BusinessEntityVO) => {
  try {
    await proxy?.$modal.confirm('确认要取消该主体的认证吗？');
    await cancelCertification(row.id);
    proxy?.$modal.msgSuccess('取消认证成功');
    await getList();
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  getRegionManagementList();
  getList();
});
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

:deep(.el-card__header) {
  padding: 12px 20px;
  background-color: #f5f7fa;
}
</style>
